// 登录状态检查和路由守卫工具
import { isLoggedIn, clearLoginInfo } from './user.js'

// 需要登录才能访问的页面路径
const AUTH_PAGES = [
  '/pages/my/index',
  '/pages/my/certificate',
  '/pages/my/completeInfo',
  '/pages/volunteer/index',
  '/pages/volunteer/detail',
  '/pages/vip/index',
  '/pages/vip/detail',
  '/pages/contributions/index',
  '/pages/moneyAndMaterials/index',
  '/pages/moneyAndMaterials/detail',
  '/pages/blood/index',
  '/pages/blood/detail',
  '/pages/jiuhu/index',
  '/pages/jiuyuan/index',
  '/pages/jiuzhu/index',
  '/pages/qiguan/index',
  '/pages/zaogan/index'
]

// 不需要登录就能访问的页面路径
const PUBLIC_PAGES = [
  '/pages/index/index',
  '/pages/login/index'
]

// 检查页面是否需要登录
export const needAuth = (path) => {
  return AUTH_PAGES.some(authPath => path.startsWith(authPath))
}

// 检查页面是否为公开页面
export const isPublicPage = (path) => {
  return PUBLIC_PAGES.some(publicPath => path.startsWith(publicPath))
}

// 检查登录状态
export const checkLoginStatus = () => {
  // 检查是否已登录
  return isLoggedIn()
}

// 路由守卫
export const routeGuard = (to) => {
  // 如果是公开页面，直接放行
  if (isPublicPage(to)) {
    return true
  }
  
  // 检查登录状态
  if (!checkLoginStatus()) {
    // 未登录或token过期，跳转到登录页
    uni.reLaunch({
      url: '/pages/login/index'
    })
    return false
  }
  
  return true
}

// 应用启动时的登录状态检查
export const initAuth = () => {
  // 检查当前页面路径
  const pages = getCurrentPages()
  if (pages.length > 0) {
    const currentPage = pages[pages.length - 1]
    const currentPath = '/' + currentPage.route
    
    // 如果不是公开页面且未登录，跳转到登录页
    if (needAuth(currentPath) && !checkLoginStatus()) {
      uni.reLaunch({
        url: '/pages/login/index'
      })
    }
  }
}

// 退出登录
export const logout = () => {
  clearLoginInfo()
  uni.reLaunch({
    url: '/pages/login/index'
  })
} 